package com.example.cardgame.model

class CardMatchingGame(val count: Int)  {
    var score = 0

    val cards: MutableList<Card>
    val selectCards = ArrayList<Int>();

    init {
        val deck = Deck()
        cards = mutableListOf()
        for (i in 1..count) {
            val card: Card? = deck.drawRandomCard()
            if (card != null) {
                cards.add(card)
            }
        }
    }

    fun reset(){
        val deck = Deck()
        score = 0
        cards.clear()
        for (i in 1..count) {
            val card: Card? = deck.drawRandomCard()
            if (card != null) {
                cards.add(card)
            }
        }
    }

    fun cardAtIndex(index: Int): Card {
        return cards.get(index)
    }

    val MISMATCH_PENALTY = 2
    val MATCH_BONUS = 4
    val COST_TO_CHOOSE = 1

    fun chooseCardAtIndex(index: Int) {
        val card= cardAtIndex(index)
        if (!card.isMatched) {
            if (card.isChosen) {
                card.isChosen = false
            } else {
                    if (selectCards.size == 1) {
                        val matchScore = card.match(arrayOf(cardAtIndex(selectCards[0])))
                        if (matchScore == 0) {
                           score -= MISMATCH_PENALTY
                            cardAtIndex(selectCards[0]).isChosen = false
                            selectCards.removeAt(0)
                        }
                    }
                if (selectCards.size == 2) {
                    val matchScore = card.match(arrayOf(cardAtIndex(selectCards[0]),cardAtIndex(selectCards[1])))
                    if (matchScore > 0) {
                        score += matchScore * MATCH_BONUS
                        cardAtIndex(selectCards[0]).isMatched = true
                        cardAtIndex(selectCards[1]).isMatched = true
                        card.isMatched = true
                    }else {
                        score -= MISMATCH_PENALTY * 2
                        cardAtIndex(selectCards[0]).isChosen = false
                        cardAtIndex(selectCards[1]).isChosen = false

                    }
                    selectCards.clear()
                }
            }
            score -= COST_TO_CHOOSE
            card.isChosen = true
            if (!card.isMatched && card.isChosen ) selectCards.add(index);
        }
    }
}